{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow.keras as keras\n",
    "import pandas as pd\n",
    "import tensorflow.compat.v1 as tf\n",
    "tf.disable_v2_behavior()\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "(xv,yv), (x_test,y_test) = keras.datasets.mnist.load_data()  #numpy中的格式\n",
    "xv = xv.reshape(60000,784)\n",
    "yv = pd.get_dummies(yv).values\n",
    "x_test = x_test.reshape(10000,784)\n",
    "y_test = pd.get_dummies(y_test).values\n",
    "batch_size = 1000\n",
    "iteration = xv.shape[0]/batch_size\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "第1次训练后，准确度accuracy为：0.898200\n",
      "第2次训练后，准确度accuracy为：0.910600\n",
      "第3次训练后，准确度accuracy为：0.906600\n",
      "第4次训练后，准确度accuracy为：0.905500\n",
      "第5次训练后，准确度accuracy为：0.910500\n",
      "第6次训练后，准确度accuracy为：0.912600\n",
      "第7次训练后，准确度accuracy为：0.915300\n",
      "第8次训练后，准确度accuracy为：0.905900\n",
      "第9次训练后，准确度accuracy为：0.918900\n",
      "第10次训练后，准确度accuracy为：0.921800\n",
      "第11次训练后，准确度accuracy为：0.916400\n",
      "第12次训练后，准确度accuracy为：0.920900\n",
      "第13次训练后，准确度accuracy为：0.914700\n",
      "第14次训练后，准确度accuracy为：0.914000\n",
      "第15次训练后，准确度accuracy为：0.921900\n",
      "第16次训练后，准确度accuracy为：0.918300\n",
      "第17次训练后，准确度accuracy为：0.909500\n",
      "第18次训练后，准确度accuracy为：0.920700\n",
      "第19次训练后，准确度accuracy为：0.913600\n",
      "第20次训练后，准确度accuracy为：0.923000\n"
     ]
    }
   ],
   "source": [
    "\n",
    "x = tf.placeholder(tf.float32,[None,784])\n",
    "#定义用于输出的placeholder\n",
    "y = tf.placeholder(tf.float32,[None,10])\n",
    "#构建一个输入层为784，输出层为10 的神经网络\n",
    "W = tf.Variable(tf.zeros([784,10]))\n",
    "b = tf.Variable(tf.zeros([10]))\n",
    "x_w_b = tf.matmul(x,W) + b\n",
    "#使用softmax激活函数\n",
    "prediction = tf.nn.softmax(x_w_b)\n",
    "#使用二次代价函数\n",
    "loss = tf.losses.mean_squared_error(y,prediction)\n",
    "#设置学习率,使用AdamOptimizer学习率要小些\n",
    "lr = 0.001\n",
    "#使用AdamOptimizer优化器\n",
    "optimizer = tf.train.AdamOptimizer(lr)\n",
    "#最小化损失函数\n",
    "train = optimizer.minimize(loss)\n",
    "#变量初始化\n",
    "init = tf.global_variables_initializer()\n",
    "#结果存放在一个布尔型列表中\n",
    "#argmax返回一维张量中最大的值所在的位置\n",
    "correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))\n",
    "#求预测准确率\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n",
    "#创建session训练网络\n",
    "with tf.Session() as session:\n",
    "    #数据初始化\n",
    "    session.run(init)\n",
    "    #训练20遍\n",
    "    for epoch in range(1,21):\n",
    "        for batch_step in range(0,int(iteration)):\n",
    "            batch_x  =  xv[batch_step*batch_size:(batch_step + 1)*batch_size,:]\n",
    "            batch_y =   yv[batch_step*batch_size:(batch_step + 1)*batch_size,:]\n",
    "            session.run(train,feed_dict={x:batch_x,y:batch_y})\n",
    "        #用测试数据计算准确度\n",
    "        accu = session.run(accuracy,feed_dict={x:x_test,y:y_test})\n",
    "        print(\"第%i次训练后，准确度accuracy为：%.6f\"%(epoch,accu))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
